const Koa = require('koa')
const router = require('koa-router')()
const app = new Koa()
const json = require('koa-json')
const logger = require('koa-logger') // 引入各种依赖
const jwt = require('koa-jwt')
const auth = require('./server/routes/auth.js')
const api = require('./server/routes/api.js')

app.use(require('koa-bodyparser')())
app.use(json())
app.use(logger())

app.use(async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    if (error.status === 401) {
      ctx.status = 401
      ctx.body = {
        success: false,
        token: null,
        info: 'Protected resource, use Authorization header to get access'
      }
    } else {
      throw error
    }
  }
})

app.on('error', function (err, ctx) {
  console.log('server error', err)
})

router.use('/auth', auth.routes())
router.use(jwt({ secret: 'vue-koa-todolist' }).unless({ path: [/\/api/] }))
router.use('/api', api.routes())

app.use(router.routes())

// router.get('/auth/user/:id', async (ctx, next) => {
//   ctx.response.type = 'text/html'
//   ctx.response.body = '<h1>hello,koa2!</h1>'
// })
// app.use(router.routes())

app.listen(8889, () => {
  console.log('Koa is listening in 8889')
})

module.exports = app
